
treeMI <- function (thedata, ITER = 10, factorvar, starter = TRUE,
 initdata = NULL, PPDdraw = FALSE, minCut = 5,
  minDev = 1e-04, startCut = 10, startDev = 1e-04) 
{
	if(! is.data.frame(thedata)) stop("`thedata' must be a data.frame")
	PPDhold <- NULL
    varmiss <- colSums(is.na(thedata)) > 0
    if (max(varmiss == 1)) 
        misscol <- varmiss * c(1:ncol(thedata))
    if (max(varmiss > 1)) 
        misscol = varmiss
    misscol <- misscol[misscol > 0]
    imp1 <- thedata
    if (PPDdraw) 
        PPDhold <- thedata
    else PPDhold <- NULL    
    if (sum(factorvar) > 0) {
        for (i in 1:ncol(thedata)) {
            if (factorvar[i] == 1) 
                imp1[, i] <- as.factor(imp1[, i])
        }
    }
    colOrder <- order(colSums(is.na(thedata[, misscol])))    
    if(starter){
    comdata <- imp1[, varmiss == 0]
    #permCol <- sample(1:length(misscol))
    #for (i in permCol) {
    	for(i in colOrder){
    	tryAgain <- TRUE
    	minCutTmp <- startCut
    	while(tryAgain){
    	tryCatch({
        treeimp <- tree(imp1[, misscol[i]] ~ ., data = comdata, 
            mincut = minCutTmp, mindev = startDev, na.action = na.omit)
            tryAgain=FALSE},
            error = function(e){cat("incrementing minCut by one\n")},
            	{minCutTmp <- minCutTmp + 1 
            		tryAgain=TRUE})}
            	
            
        imputes <- treedraw(treeimp, comdata[is.na(imp1[, misscol[i]]), 
            ], factorvar[misscol[i]])
        comdata = cbind(comdata, imp1[, misscol[i]])
        names(comdata)[ncol(comdata)] <- names(imp1)[misscol[i]]
        comdata[is.na(comdata[, ncol(comdata)]), ncol(comdata)] <- imputes
        imp1[is.na(imp1[, misscol[i]]), misscol[i]] <- imputes
    }
    }
    if (!starter) {
        imp1 <- initdata}
    if(PPDdraw){    
    PPDhold <- imp1}    
    for (j in 1:ITER) {
        for (i in colOrder) {
            newdata <- imp1[, -misscol[i]]
            newPPD <- PPDhold[,-misscol[i]]
    	tryAgain <- TRUE
    	minCutTmp <- minCut
    	while(tryAgain){
    	tryCatch({
        treeimp <- tree(imp1[, misscol[i]] ~ ., data = newdata, 
            mincut = minCutTmp, mindev = minDev); tryAgain=FALSE},
            error = function(e){cat("incrementing minCut by one\n")},
            	{minCutTmp <- minCutTmp + 1 
            		tryAgain=TRUE})
            	}

            if (PPDdraw) {
                PPDdrawImp <- treedraw(treeimp, newPPD, factorvar[misscol[i]])
                PPDhold[, misscol[i]] <- PPDdrawImp
            }
            imputes <- treedraw(treeimp, newdata[is.na(thedata[, 
                misscol[i]]), ], factorvar[misscol[i]])
            imp1[is.na(thedata[, misscol[i]]), misscol[i]] <- imputes
        }
    }
    if (PPDdraw) 
        return(list(impSet = imp1, PPDsample = PPDhold))
    else return(imp1)
}
